package com.momoc.multi.chat.room.common.config;

import com.momoc.multi.chat.room.common.utils.AssertUtil;
import com.momoc.multi.chat.room.common.utils.RedisUtils;
import com.momoc.multi.chat.room.core.filter.FilterTest;
import com.momoc.netty.frame.config.SmartNettyProperties;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;


/**
 * 用于清理redis中重启造成的缓存泄露问题，正常来说不会有
 * @author momoc
 * @version 1.0
 * @className ClearRedisCache
 * @description
 * @date 2024/5/29 14:08
 */
@Configuration
public class ClearRedisCache implements CommandLineRunner {

    Logger log = LoggerFactory.getLogger(ClearRedisCache.class);

    public static String ONLINE_LIST_KEY = "online_list_%s";

    private RedisUtils redisUtils;

    public ClearRedisCache(SmartNettyProperties smartNettyProperties, RedisUtils redisUtils) {
        ONLINE_LIST_KEY = String.format(ONLINE_LIST_KEY, SmartNettyProperties.getNettyProperties().getMachineId());
        this.redisUtils = redisUtils;
    }

    //增加到清理队set中
    public void addClearSet(String userid) {
        redisUtils.addSet(ONLINE_LIST_KEY, userid);
    }

    public void clearOne(String userid) {
        redisUtils.removeSet(ONLINE_LIST_KEY, userid);
    }


    //清理上次已离线的用户队列
    @Override
    public void run(String... args) throws Exception {


        log.info("clear redis user connect cache start ");
        List<String> userIds = redisUtils.popSet(ONLINE_LIST_KEY);

        while (!AssertUtil.isEmpty(userIds)) {
            redisUtils.removeKeys(userIds);
            userIds = redisUtils.popSet(ONLINE_LIST_KEY);
        }
        log.info("clear redis user connect cache end ");

    }
}
